package com.leyou.user.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.IUserService;
import com.leyou.user.vo.UserVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.*;

/**
 * @author xiuer
 * @description 用户中心业务层
 * @create 2019/7/6 20:26
 */
@Service
public class UserServiceImpl implements IUserService {
    private static final String KEY_PREFIX = "verify:code:phone:";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户数据的校验
     *
     * @param data 校验的数据
     * @param type 1. 用户名，2 手机
     * @return
     */
    @Override
    public Boolean verifyUserMsg(String data, Integer type) {
        User user = new User();
        if (type == 1) {
            user.setUsername(data);
        } else if (type == 2) {
            user.setPhone(data);
        } else {
            //传入3时 抛异常请求参数有误！
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        int affectRows = userMapper.selectCount(user);
        return affectRows == 0;
    }

    /**
     * 生成手机验证码
     */
    @Override
    public void sendPhoneCode(String phone) {

        if (!RegexUtils.isPhone(phone)) {
            //手机号码格式不正确
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        //生成验证码 设置 有效时间
        String code = RandomStringUtils.randomAlphanumeric(6);
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 300, TimeUnit.MINUTES);
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        //存入redis
        //发送MQ 到消息ly-sms 微服务
        amqpTemplate.convertAndSend(Exchange.SMS_EXCHANGE_NAME, RoutingKey.VERIFY_CODE_KEY, map);
    }

    /**
     * 用户注册
     *
     * @param userDTO
     * @param code
     */
    @Override
    @Transactional
    public void register(UserDTO userDTO, String code) {
        //校验参数 接收的实体类已校验

        //校验验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + userDTO.getPhone());
        if (!code.equalsIgnoreCase(cacheCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //密码加密
        userDTO.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        //保存用户信息 写入数据库
        int affectRows = userMapper.insertSelective(BeanHelper.copyProperties(userDTO, User.class));
        if (affectRows != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /**
     * 根据用户名密码查询用户信息
     */
    @Override
    public UserVO queryUserInfo(String username, String password) {
        User user = new User();
        user.setUsername(username);
        User result = userMapper.selectOne(user);
        if (result == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        if (!passwordEncoder.matches(password, result.getPassword())) {

            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        return BeanHelper.copyProperties(result, UserVO.class);
    }
}
